package com.fw.kafka_chapter_1.concumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

/**
 * @Author:yanwei
 * @Date: 2020/8/16 - 17:48
 *
 * Kafka 消息接受者
 */
@Slf4j
public class ConcumerAsyncCommit {

    public static void main(String[] args) {
        Properties properties = new Properties();
        // key 序列化器指定
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        // value 序列化执行
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        // 指定组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"fw_group");
        // 指定连接
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.227.129:9092");
        //设置手动提交开启
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,Boolean.FALSE);
        //创建接收器
        KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(properties);


        // 指定 topic
        consumer.subscribe(Collections.singletonList("fw"));

        while (true){
            // 10 毫秒获取一次
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(10));
            for (ConsumerRecord<String, String> stringStringConsumerRecord : poll) {
                System.err.println(stringStringConsumerRecord.value());
            }
            // 同步提交
            consumer.commitAsync(new OffsetCommitCallback() {
                @Override
                public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception e) {
                    if (Objects.isNull(e)){
                        // 正常
                        System.out.println(offsets);
                    }else{
                        // 异常发生
                        System.out.println(e.getMessage());
                    }
                }
            });
        }
    }
}
